#####################################
#############ADS-B接收###############
#####################################

#################################### 函数库
import numpy as np
import adi
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import pyModeS as pms
from timeit import default_timer as timer
from numba import jit
import queue
#################################### 配置pluto
# 连接硬件
sdr = adi.Pluto("ip:192.168.2.1")
# 采样率
FS = 4e6
sdr.sample_rate = int(4e6)
# 增益模式
sdr.gain_control_mode = "slow_attack"
# 接收带宽
sdr.rx_rf_bandwidth = int(4e6)
# 接收中心频率
sdr.rx_lo = int(1090e6)
# 接收数据输出类型
sdr.rx_output_type = 'double'
# 接收数据块长度
sdr.rx_buffer_size = 400000
#################################### 函数
@jit(nopython=True)
def FindPreamble(data):
    preamble = []
    i = 0
    while i<LEN:
        if data[i] & data[i+A] & data[i+B] & data[i+C]:
            preamble.append(i)
            i += M
        else:
            i += 1
    return preamble


@jit(nopython=True)
def DecodeADS(preamble, data):
    msg = []
    for k in preamble:
        target = data[k:k+M]
        mes = []
        for i in loc:
            if target[i] & (not target[i+2]):
                mes.append('1')
            elif (not target[i]) & target[i+2]:
                mes.append('0')
            else:
                break
        if len(mes)>110:
            msg.append(mes)
    return msg


def ADSdecode(message):
    #global test
    if len(message)>0:
        for i in message:
            i = ''.join(i)
            ads = str(hex(int(i,2)))[2:]
            print(pms.tell(ads)
            #test = np.append(test, ads)
            #if len(test)>500:
                #np.save('test', test)
                #print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
    return 0


# 读取数据
def ReadRx():
    tic = timer()
    data = np.abs(sdr.rx())
    cache.put(data)
    toc = timer()
    print('读取耗时：', toc - tic, '秒') # 输出的时间，秒为单位


# 数据处理更新
def Process():
    tic = timer()
    data = cache.get()
    data = np.greater(data, TH)
    pre = FindPreamble(data)
    msg = DecodeADS(pre, data)
    ADSdecode(msg)
    toc = timer()
    print('处理耗时：', toc - tic, '秒') # 输出的时间，秒为单位
########################################### 常数
n = int(FS/2e6)
N = 10*n
M = 240*n
A = 2*n
B = 7*n
C = 9*n
########################################### 测试
test = np.array([])
########################################### 预处理
cache = queue.Queue(maxsize=1000)
data = sdr.rx()
LEN = len(data)-M

loc = np.arange(16*n,M,2*n)

TH = np.sum(np.abs(data))/len(data)*6
print('门限：', TH)
########################################### 界面
app = QtGui.QApplication([])
win = pg.GraphicsLayoutWidget(show=True, title="Basic plotting examples")
#win.resize(1200,500)
#win.setWindowTitle('Pluto Rx')
#pg.setConfigOptions(antialias=True)

timer1 = QtCore.QTimer()
timer1.timeout.connect(ReadRx)
timer1.start()

timer2 = QtCore.QTimer()
timer2.timeout.connect(Process)
timer2.start()


if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()